package com.hxh.utils
{
	import flash.display.CapsStyle;
	import flash.display.GradientType;
	import flash.display.LineScaleMode;
	import flash.display.Sprite;
	import flash.geom.Matrix;
	
	/**
	 * Drawings utilities  
	 */
	public class Drawings
	{
		public function Drawings(){}
		
		/**
		 * <p>
		 * Draw a color spectrum bar<br />
		 * Credit to http://www.boostworthy.com for his maths and code
		 * </p>
		 * @param width The width of the spectrum bar
		 * @param height The height of the spectrum bat
		 * @return A spectrum bar sprite object
		 */
		public static function ColorSpectrumBar(width:Number, height:Number):Sprite{
			
			var sprite:Sprite = new Sprite();
			
			var nColorPercent : Number;
			var nRadians      : Number;
			var nR            : Number;
			var nG            : Number;
			var nB            : Number;
			var nColor        : Number;
			var objMatrixW    : Matrix;
			var objMatrixB    : Matrix;
			var nHalfHeight   : Number;
			
			// Calculate half of the height.
			nHalfHeight = height * 0.5;
			
			// Loop through all of the pixels from '0' to the specified width.
			for(var i:int = 0; i < width; i++)
			{
				// Calculate the color percentage based on the current pixel.
				nColorPercent = i / width;
				
				// Calculate the radians of the angle to use for rotating color values.
				nRadians = (-360 * nColorPercent) * (Math.PI / 180);
				
				// Calculate the RGB channels based on the angle.
				nR = Math.cos(nRadians)                   * 127 + 128 << 16;
				nG = Math.cos(nRadians + 2 * Math.PI / 3) * 127 + 128 << 8;
				nB = Math.cos(nRadians + 4 * Math.PI / 3) * 127 + 128;
				
				// OR the individual color channels together.
				nColor  = nR | nG | nB;
				
				// Create new matrices for the white and black gradient lines.
				objMatrixW = new Matrix();
				objMatrixW.createGradientBox(1, nHalfHeight, Math.PI * 0.5, 0, 0);
				objMatrixB = new Matrix();
				objMatrixB.createGradientBox(1, nHalfHeight, Math.PI * 0.5, 0, nHalfHeight);
				
				// Each color slice is made up of two lines - one for fading from white to the 
				// color, and one for fading from the color to black.
				sprite.graphics.lineStyle(1, 0, 1, false, LineScaleMode.NONE, CapsStyle.NONE);
				sprite.graphics.lineGradientStyle(GradientType.LINEAR, [0xFFFFFF, nColor], [100, 100], [10, 255], objMatrixW);
				sprite.graphics.moveTo(i, 0);
				sprite.graphics.lineTo(i, nHalfHeight);
				sprite.graphics.lineGradientStyle(GradientType.LINEAR, [nColor, 0], [100, 100], [0, 245], objMatrixB);
				sprite.graphics.moveTo(i, nHalfHeight);
				sprite.graphics.lineTo(i, height);
			}
			return sprite;	
		}
	}
}